import type { UserInfo } from '../types/user';

// 模拟用户数据
const mockUsers: Record<string, UserInfo> = {
  'suixia': {
    id: 'user001',
    username: 'suixia',
    password: 'Password@123', // 在实际项目中，密码应该是加密存储的
    avatar: '',
    userType: 'merchant',
    email: 'suixi@example.com',
    phone: '13800138000',
    createTime: '2023-01-01T00:00:00Z',
    permissions: ['create_site', 'manage_products', 'view_orders']
  },
  'admin1': {
    id: 'user002',
    username: 'admin1',
    password: 'Admin@123',
    avatar: '',
    userType: 'admin',
    email: 'admin@example.com',
    phone: '13900139000',
    createTime: '2023-01-02T00:00:00Z',
    permissions: ['all'] // 管理员拥有所有权限
  },
  'user1': {
    id: 'user003',
    username: 'user1',
    password: 'User@123',
    avatar: '',
    userType: 'user',
    email: 'user@example.com',
    phone: '13700137000',
    createTime: '2023-01-03T00:00:00Z',
    permissions: ['view_profile', 'view_products']
  }
};

/**
 * 模拟用户登录API
 * @param username 用户名
 * @param password 密码
 * @returns 用户信息或null（登录失败）
 */
export const loginApi = async (username: string, password: string): Promise<UserInfo | null> => {
  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 500));
  
  const user = mockUsers[username];
  if (user && user.password === password) {
    // 不返回密码信息
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const { password: _, ...userWithoutPassword } = user;
    return userWithoutPassword as UserInfo;
  }
  
  return null;
};

/**
 * 模拟获取用户信息API
 * @param username 用户名
 * @returns 用户信息
 */
export const getUserInfoApi = async (username: string): Promise<UserInfo | null> => {
  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 300));
  
  const user = mockUsers[username];
  if (user) {
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const { password: _, ...userWithoutPassword } = user;
    return userWithoutPassword as UserInfo;
  }
  
  return null;
};

/**
 * 模拟更新用户信息API
 * @param userId 用户ID
 * @param userData 要更新的用户数据
 * @returns 更新后的用户信息或null（更新失败）
 */
export const updateUserInfoApi = async (userId: string, userData: Partial<UserInfo>): Promise<UserInfo | null> => {
  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 400));
  
  // 查找用户
  const userKey = Object.keys(mockUsers).find(key => mockUsers[key].id === userId);
  if (userKey) {
    // 更新用户信息
    mockUsers[userKey] = {
      ...mockUsers[userKey],
      ...userData
    };
    
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const { password: _, ...userWithoutPassword } = mockUsers[userKey];
    return userWithoutPassword as UserInfo;
  }
  
  return null;
};